﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class Inventory : MonoBehaviour
{
    public static Inventory _instance;


    public Canvas canvas;
    public inventory_static_grid helmet;// 头部
    public inventory_static_grid wrist;// 手腕
    public inventory_static_grid shoe;// 双脚
    public inventory_static_grid legs; // 腿部
    public inventory_static_grid armor; // 护甲

    public inventory_static_grid main_weapon; // 主武器
    public inventory_static_grid sub_weapon; // 副武器

    public Transform Item_prefabs;// 物品的prefabs

    public static int Base_Aggressity = 8;
    public int Aggressity = Base_Aggressity;
    public int anti_Radiation_Percentage = 0;

    public bool isShow = false;
    public int MaxLoad = 3200;// 最大荷载量
    public int Load = 0; // 当前荷载量

    public List<inventory_static_grid> item_list = new List<inventory_static_grid>();

    private int index;// 当前道具的编号

    private void Awake()
    {
        _instance = this;
    }

    // Start is called before the first frame update
    void Start()
    {
        helmet = transform.Find("helmet").GetComponent<inventory_static_grid>();
        wrist = transform.Find("wrist").GetComponent<inventory_static_grid>();
        shoe = transform.Find("shoe").GetComponent<inventory_static_grid>();
        legs = transform.Find("leg").GetComponent<inventory_static_grid>();
        armor = transform.Find("armor").GetComponent<inventory_static_grid>();

        main_weapon = transform.Find("main_weapon").GetComponent<inventory_static_grid>();
        sub_weapon = transform.Find("sub_weapon").GetComponent<inventory_static_grid>();

        Add_ItemByID(3002);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.T))
        {
            Debug.Log("你按下了T键");
            Execute_CraftTable(CraftTableInfo._instance.getCraftinfobyid(2));
            //Debug.Log("合成结束后格子的id：" + item_list[0].Get_item_inside().id);
            Debug.Log("T updateinfo: " + item_list[0].Get_item_inside().id);
        }
        if (Input.GetKeyDown(KeyCode.Y))
        {
            int id;
            id = Random.Range((int)0, (int)ObjectsInfo._instance.object_dic.Count);
            Add_ItemByID(ObjectsInfo._instance.object_dic[id].id);
        }
    }
    // 调出所谓的UI
    public void TransformState()
    {
        if (isShow == false)
        {
            isShow = true;
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
            this.transform.DOLocalMove(new Vector3(0, 0, 0), 1.0f).SetUpdate(true);
            //Time.timeScale = 0;
        }
        else
        {
            isShow = false;
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
            this.transform.DOLocalMove(new Vector3(+1000, 0, 0), 1.0f).SetUpdate(true);
            //Time.timeScale = 1;
        }
    }

    // 拾取物品，并添加到物品栏里面去
    public bool Add_ItemByID(int id, int num = 1)
    {
        if (ObjectsInfo._instance.getObjectinfobyid(id) == null)
        {
            Debug.Log("没有对应id的道具");
            return false;
        }

        // 检查是否有重复的物品
        inventory_static_grid storedGrid = null;
        foreach (inventory_static_grid theGrid in item_list)
        {
            if(theGrid.Can_Be_Add(id) == inventory_static_grid.OKAY)
            {
                storedGrid = theGrid;
                break;
            }
        }
        if(storedGrid == null)// 如果没有找到可以叠加的物品
        {
            foreach(inventory_static_grid theGrid in item_list)
            {
                if(theGrid.id == 0)
                {
                    storedGrid = theGrid;
                    break;
                }
            }
            // 如果没有找到能够容纳的盒子
            if(storedGrid == null)
            {
                Debug.Log("背包已经满了");
                return false;
            }
            else
            {
                // 能找到能够容纳的格子就在那个各自下面创建一个子物体
                Transform prop = Instantiate(Item_prefabs, storedGrid.transform);
                prop.transform.localPosition = Vector3.zero;
                storedGrid.SetId(id);

                //Debug.Log("获得物品id:" + id.ToString());
                //Debug.Log("After Add_Item id: " + storedGrid.id);
            }
        }
        // 如果存在能够叠加的槽
        else
        {
            storedGrid.GetComponentInChildren<inventory_movable_item>().Get_Some(num);
        }

        Get_Load();
        return true;
    }

    // 拾取具体物品，并添加到物品栏去
    public bool Add_Concrete_Item(Objectinfo a_prop, int num = 1)
    {
        int objID = a_prop.id;
        // 检查是否有重复的物品
        inventory_static_grid storedGrid = null;
        foreach (inventory_static_grid theGrid in item_list)
        {
            if (theGrid.Can_Be_Add(objID) == inventory_static_grid.OKAY)
            {
                storedGrid = theGrid;
                break;
            }
        }
        // 如果没有找到可以叠加的物品
        if (storedGrid == null)
        {
            // 在遍历一次找找有没有空的格子
            foreach (inventory_static_grid theGrid in item_list)
            {
                if (theGrid.id == 0)
                {
                    storedGrid = theGrid;
                    break;
                }
            }
            // 如果没有找到能够容纳的盒子（也就是满背包）
            if (storedGrid == null)
            {
                Debug.Log("背包已经满了");
                return false;
            }
            else
            {
                // 能找到能够容纳的格子就在那个各自下面创建一个子物体
                Transform prop = Instantiate(Item_prefabs, storedGrid.transform);
                Debug.Log("子格已创建");
                prop.transform.localPosition = Vector3.zero;
                storedGrid.Set_Prop(a_prop);
            }
        }
        // 如果存在能够叠加的槽 直接叠加
        else
        {
            storedGrid.GetComponentInChildren<inventory_movable_item>().Get_Some(num);
        }

        Get_Load();
        return true;
    }

    // 计算所有物品的负载量
    public void Get_Load()
    {
        int load = 0;
        foreach(inventory_static_grid one_grid in item_list)
        {
            load += one_grid.Get_Wight();
        }
        Load = load;
        Debug.Log("当前质量：" + Load.ToString());
    }
    
    // 计算超重减益的百分比
    public int GetDebuff()
    {
        if (MaxLoad > Load) return 100;
        else return 100 * MaxLoad / Load;
    }

    // 寻找所有的药品，并自动服用
    public void Get_Fast_Cure()
    {
        int maxHP = 0;
        int index = -1;

        for(int i = 0; i < item_list.Count; i++)
        {
            int cure_point = item_list[i].Get_Cure_Point();
            if(cure_point > maxHP)
            {
                index = i;
                maxHP = cure_point;
            }
        }
        if (maxHP == 0 || index == -1)
        {
            Debug.Log("没有可以回血的道具了");
        }
        else
        {
            item_list[index].acitivate_Prop();
            Debug.Log("使用了回血的道具");
        }
    }

    // 破坏装备区的护甲，并返回还需要继续计算的护甲值
    public int BreakArmor(int break_point)
    {
        if(armor.id == 0)// 如果根本没有装护甲
        {
            return break_point;
        }
        else
        {
            inventory_movable_item the_Armor = armor.Get_item_inside();
            if(the_Armor == null)
            {
                Debug.Log("armor error");
                return break_point;
            }
            else
            {
                Objectinfo info = the_Armor.GetObjectinfo();
                info.armor -= break_point;
                if (info.armor < 0)
                {
                    int last = -info.armor;

                    Destroy(the_Armor.gameObject);
                    armor.Clear_Grid();
                    return last;
                }
                else
                    return 0;
            }
        }
    }
    // 更新装备区的属性
    public void Refresh_Equip_Attibute()
    {
        int new_Aggressity = Base_Aggressity;
        int new_anti_Radiation = 0;
        inventory_movable_item equipment_Item = helmet.Get_item_inside();
        if(equipment_Item != null)
        {
            new_anti_Radiation += equipment_Item.GetObjectinfo().anti_rad;
            new_Aggressity += equipment_Item.GetObjectinfo().damage;
        }
        equipment_Item = wrist.Get_item_inside();
        if (equipment_Item != null)
        {
            new_anti_Radiation += equipment_Item.GetObjectinfo().anti_rad;
            new_Aggressity += equipment_Item.GetObjectinfo().damage;
        }
        equipment_Item = shoe.Get_item_inside();
        if (equipment_Item != null)
        {
            new_anti_Radiation += equipment_Item.GetObjectinfo().anti_rad;
            new_Aggressity += equipment_Item.GetObjectinfo().damage;
        }
        equipment_Item = legs.Get_item_inside();
        if (equipment_Item != null)
        {
            new_anti_Radiation += equipment_Item.GetObjectinfo().anti_rad;
            new_Aggressity += equipment_Item.GetObjectinfo().damage;
        }
        equipment_Item = armor.Get_item_inside();
        if (equipment_Item != null)
        {
            new_anti_Radiation += equipment_Item.GetObjectinfo().anti_rad;
            new_Aggressity += equipment_Item.GetObjectinfo().damage;
        }
        equipment_Item = main_weapon.Get_item_inside();
        if (equipment_Item != null)
        {
            new_anti_Radiation += equipment_Item.GetObjectinfo().anti_rad;
            new_Aggressity += equipment_Item.GetObjectinfo().damage;
        }
        equipment_Item = sub_weapon.Get_item_inside();
        if (equipment_Item != null)
        {
            new_anti_Radiation += equipment_Item.GetObjectinfo().anti_rad;
            new_Aggressity += equipment_Item.GetObjectinfo().damage;
        }

        Aggressity = new_Aggressity;
        anti_Radiation_Percentage = new_anti_Radiation;
    }
    // 获得装备区的攻击力
    public int Get_Aggressity()
    {
        return Aggressity;
    }
    public int Get_Radiation_Percentage()
    {
        return anti_Radiation_Percentage;
    }
    // 检查是否在背包中有对应的物品和对应的个数
    public bool Check_For_Specific_Item(int id, int count)
    {
        int sum = 0;
        bool result = false;
        // 检查是不是每一个都有
        foreach (inventory_static_grid Grid in item_list)
        {
            inventory_movable_item item = Grid.Get_item_inside();
            // 当然要先确认这个盒子里面有没有东西
            if (item != null)
            {
                // 如果是同一样物品，则等到物品
                if(item.GetObjectinfo().id == id)
                {
                    sum += item.Get_Count();
                    if(sum >= count)
                    {
                        result = true;
                        break;
                    }
                }
            }
        }
        return result;
    }
    public bool Cost_Specific_Item(int id, int count)
    {
        int rest = count;
        foreach (inventory_static_grid Grid in item_list)
        {
            inventory_movable_item Item = Grid.Get_item_inside();
            if(Item != null)
            {
                Objectinfo Objects = Item.GetObjectinfo();
                if(Objects.id == id)
                {
                    // 如果剩下的数目足够
                    if(Item.Get_Count() >= rest)
                    {
                        Item.Get_Some(-rest);
                        return true;
                    }
                    else// 如果剩下的数目不够就直接扣完
                    {
                        Item.Get_Some(-Item.Get_Count());
                        rest -= Item.Get_Count();
                    }
                }
            }
        }
        Debug.Log("Item Capacity Wrong");
        return false;
    }

    // 检查背包中是否又满足某个合成表的物资
    public bool Check_For_CraftTable(CraftTable table)
    {
        int index = 0;
        for(;index < table.mat_id.Count; index++)
        {
            int id = table.mat_id[index];
            int count = table.mat_num[index];
            // 如果没能发现
            if(!Check_For_Specific_Item(id, count))
            {
                Debug.Log("有物资缺乏！数量：" + count.ToString() + " 物品：" + id.ToString());
                return false;
            }
        }

        return true;
    }
    // 进行建造
    public int Execute_CraftTable(CraftTable table)
    {
        // 如果实际上根本没有办法实现
        if (!Check_For_CraftTable(table)) return -1;
        int index = 0;

        for (;index < table.mat_id.Count; index ++)
        {
            int id = table.mat_id[index];
            int count = table.mat_num[index];

            Cost_Specific_Item(id, count);
        }
        Add_ItemByID(table.targetid);
        Debug.Log("合成成功" + table.targetid);

        return 1;
    }

    // 获得主武器的冷却时间
    public float Get_Main_Weapon_CoolDown()
    {
        inventory_movable_item Main_Weapon_Item = main_weapon.Get_item_inside();
        if (Main_Weapon_Item != null)
        {
            return Main_Weapon_Item.GetObjectinfo().coldtime;
        }
        else return 0;
    }

    // 获得副武器的冷却时间
    public float Get_Sub_Weapon_CoolDown()
    {
        inventory_movable_item Sub_Weapon_item = sub_weapon.Get_item_inside();
        if (Sub_Weapon_item != null)
        {
            return Sub_Weapon_item.GetObjectinfo().coldtime;
        }
        else return 0;
    }

    /*// 穿着某个装备
    public bool Dress_Equipment(int id)
    {
        Objectinfo info = ObjectsInfo._instance.getObjectinfobyid(id);

        Transform Corres_Grid;
        // 先找到对应种类对应的格子
        switch(info.equip_Type)
        {
            case Equip_type.Armor:
                Corres_Grid = armor.transform;
                break;
            case Equip_type.Hands:
                Corres_Grid = wrist.transform;
                break;
            case Equip_type.Headgear:
                Corres_Grid = helmet.transform;
                break;
            case Equip_type.Legs:
                Corres_Grid = legs.transform;
                break;
            case Equip_type.Shoes:
                Corres_Grid = shoe.transform;
                break;
            case Equip_type.Sub_Weapon:
                Corres_Grid = sub_weapon.transform;
                break;
            case Equip_type.Weapon:
                Corres_Grid = main_weapon.transform;
                break;
            default:return false;
        }
        inventory_movable_item Item = Corres_Grid.GetComponentInChildren<inventory_movable_item>();
        // 如果这个装备下面对应的子物体不存在
        if (Item == null)
        {
            Transform the_Equipment = Instantiate(Item_prefabs, Corres_Grid);
            the_Equipment.gameObject.tag = Tags.equip_item;
            inventory_static_grid Equip_Grid = Corres_Grid.GetComponent<inventory_static_grid>();

            Equip_Grid.Set_Prop(info);
            the_Equipment.localPosition = Vector3.zero;
        }
        else// 如果存在
        {
            inventory_static_grid Equip_Grid = Corres_Grid.GetComponent<inventory_static_grid>();
            Equip_Grid.Set_Prop(info);
        }

        return true;
    }
    */
}
